#include <iostream>
#include <string>
#include <format>
#include"database.h"

//从数据库中读出Location条目的API
// 辅助函数处理可能为NULL的字段
std::string getTextColumn(sqlite3_stmt* stmt, int col) {
    const unsigned char* text = sqlite3_column_text(stmt, col);
    return text ? reinterpret_cast<const char*>(text) : "";
}


int getIntColumn(sqlite3_stmt* stmt, int col) {
    return sqlite3_column_type(stmt, col) == SQLITE_NULL ? 0 : sqlite3_column_int(stmt, col);
}

double getDoubleColumn(sqlite3_stmt* stmt, int col) {
    return sqlite3_column_type(stmt, col) == SQLITE_NULL ? 0.0 : sqlite3_column_double(stmt, col);
}
std::vector<LocationStruct> readLocations(const std::string& dbPath) {
    std::vector<LocationStruct> locations;
    sqlite3* db = nullptr;

    // 打开数据库连接
    if (sqlite3_open(dbPath.c_str(), &db) != SQLITE_OK) {
        std::cerr << "无法打开数据库: " << sqlite3_errmsg(db) << std::endl;
        return locations;
    }

    // 准备SQL语句
    const char* sql = "SELECT * FROM Location;";
    sqlite3_stmt* stmt;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
        std::cerr << "准备语句失败: " << sqlite3_errmsg(db) << std::endl;
        sqlite3_close(db);
        return locations;
    }

    // 遍历结果集
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        LocationStruct loc{};

        loc.id = sqlite3_column_int(stmt, 0); // id是主键，不能为NULL
        loc.name = getTextColumn(stmt, 1);    // name是NOT NULL
        loc.type = getTextColumn(stmt, 2);
        loc.area_type = getIntColumn(stmt, 3);
        loc.intro = getTextColumn(stmt, 4);
        loc.heat = getDoubleColumn(stmt, 5);
        loc.rating = getDoubleColumn(stmt, 6);
        loc.x = sqlite3_column_double(stmt, 7);
        loc.y = sqlite3_column_double(stmt, 8);

        locations.push_back(loc);
        if (loc.type == "景区")
            LocationTable_Spot.push_back(loc);
        else
            LocationTable_Campus.push_back(loc);
    }

    // 清理资源
    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return locations;
}


//// 示例输出
//for (const auto& loc : LocationTable) {
//    std::cout << "ID: " << loc.id << "\n"
//        << "名称: " << loc.name << "\n"
//        << "类型: " << loc.type << "\n"
//        << "区域类型: " << loc.area_type << "\n"
//        << "简介: " << loc.intro << "\n"
//        << "热度: " << loc.heat << "\n"
//        << "评分: " << loc.rating << "\n"
//        << "坐标X: " << loc.x << "\n"
//        << "坐标Y: " << loc.y << "\n"
//        << "------------------------\n";
//}







